from matplotlib import pyplot as plt
import pywebio
import numpy as np
import pandas as pd
import draw_table.draw_table

def generate_line_plot(matches, min_year, max_year, gdp):
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
    plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
    fig, ax = plt.subplots()
    years = gdp.columns[(min_year - 1959):(max_year - 1958)]  # 假设第一列是国家名称，后续列为年份和对应的GDP数据
    # 创建新的x轴坐标
    x_ticks = np.arange(len(years))
    lens = int((int(years[-1]) - int(years[0])) / 10)
    print(lens)
    print(years)
    x_ticks_labels = [year if i % lens == 0 else '' for i, year in enumerate(years)]
    plt.xticks(x_ticks, x_ticks_labels, rotation=45)

    # 创建一个空列表来存储所有选中的国家的数据
    all_selected_data = []

    for country in matches:
        selected_data = gdp[gdp['Country'] == str(country)]
        print(selected_data)

        gdp_values = selected_data.iloc[0, (min_year - 1959):(max_year - 1958)]  # 假设选择的国家数据在第一行
        print("-----------")
        print(gdp_values)
        print("-----------")
        # 插值处理
        gdp_values = pd.to_numeric(gdp_values, errors='coerce')
        gdp_values.interpolate(inplace=True)

        ax.plot(x_ticks, gdp_values, label=country, linewidth=2)
        gdp_values['Country'] = country
        all_selected_data.append(gdp_values)
    print("-----------")
    print(all_selected_data)
    print("-----------")
    # 将所有选中的国家的数据合并成一个大的DataFrame
    combined_data = pd.concat(all_selected_data, axis=1).T

    # 重置索引
    combined_data.reset_index(drop=True, inplace=True)
    print("-----------a")
    print(combined_data)
    print("-----------a")
    # 输出合并后的DataFrame
    draw_table.draw_table.output_dataframe(combined_data)


    ax.legend()
    ax.set_xlabel('Year')
    ax.set_ylabel('GDP')
    ax.set_title(f'GDP for {matches}')
    tmp_file = './output_img/plot_chart.png'
    plt.savefig(tmp_file)
    plt.close()
    pywebio.output.put_image(open(tmp_file, 'rb').read())